const db = wx.cloud.database()
const addImgUrl = 'cloud://zjn-0gzb74lr2a7692b1.7a6a-zjn-0gzb74lr2a7692b1-1317297115/image/add.png'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    name: '',
    engName: '',
    jianjie: '',
    gaishu: '',
    time: '',
    peopleInfoList: [],
    type: '',
    bofang: [],
    duration: NaN,
    imgList:['cloud://zjn-0gzb74lr2a7692b1.7a6a-zjn-0gzb74lr2a7692b1-1317297115/image/add.png'],
    chooseFlag: false,
    previewFlag: false,
    show: false,
    addImgUrl: addImgUrl,
    editFlag: false,
    uploadFlag: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  unFormatBofang(bofang) {
    var res = ''
    for (let i in bofang) {
      res = res + bofang[i]
      if (i < bofang.length - 1) {
        res = res + '、'
      }
    }

    return res
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.previewFlag || this.data.chooseFlag) {
      this.setData({ 
        previewFlag: false,
        chooseFlag: false
      })
      return
    }

    // 获取当前小程序的页面栈 
    let pages = getCurrentPages(); 
    // 数组中索引最大的页面--当前页面  
    let currentPage = pages[pages.length-1];
    var options = currentPage.options
    if (typeof(options.id) !== 'undefined') {
      var that = this
      db.collection('movies').where({
        _id: options.id
      }).get().then(res => {
        var imgList = []
        imgList.push(res.data[0].poster)
        imgList.push(addImgUrl)
        var peopleInfoList = []
        for (let i = 0; i < 3; ++i) {
          peopleInfoList[i] = {
            peopleName: res.data[0].people[i],
            peopleImage: res.data[0].peopleimage[i],
            peopleRole: res.data[0].peoplestatus[i],
            addFlag: false
          }
        }
        that.setData({
          id: res.data[0]._id,
          name: res.data[0].title,
          engName: res.data[0].translation,
          imgList: imgList,
          gaishu: res.data[0].gaishu,
          jianjie: res.data[0].jianjie,
          time: res.data[0].time,
          type: res.data[0].type,
          bofang: that.unFormatBofang(res.data[0].bofang),
          language: res.data[0].language,
          duration: res.data[0].duration,
          peopleInfoList: peopleInfoList,
          editFlag: true
        })

      })
    } else {
      this.setData({
        name: '',
        label: '',
        engName: '',
        jianjie: '',
        gaishu: '',
        time: '',
        bofang: [],
        language: '',
        duration: NaN,
        peopleInfoList: [
          {
            peopleName: '',
            peopleImage: '',
            peopleRole: '',
            addFlag: false
          },
          {
            peopleName: '',
            peopleImage: '',
            peopleRole: '',
            addFlag: false
          },
          {
            peopleName: '',
            peopleImage: '',
            peopleRole: '',
            addFlag: false
          }
        ],
        type: '',
        imgList:['cloud://zjn-0gzb74lr2a7692b1.7a6a-zjn-0gzb74lr2a7692b1-1317297115/image/add.png'],
        editFlag: false,
      })
    }
  },

  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}.${date.getMonth() + 1}.${date.getDate()}`;
  },
  onConfirm(event) {
    this.setData({
      show: false,
      time: this.formatDate(event.detail),
    });
  },

  async addPersonImg(e) {
    var idx = e.currentTarget.dataset.idx
    var that = this
      
    if (this.data.peopleInfoList[idx].addFlag || this.data.peopleInfoList[idx].peopleImage.length > 0) {
      var urls = []
      urls.push(that.data.peopleInfoList[idx].peopleImage)
      that.setData({previewFlag: true})
      await wx.previewImage({
        current: urls[0],
        urls: urls
      })

      return
    }

    that.setData({chooseFlag: true})
    await wx.chooseImage({
      count: 1,
      sourceType:['album', 'camera'],
      success(res) {
        var imgUrl = res.tempFilePaths[0]
        var peopleInfoList = that.data.peopleInfoList
        peopleInfoList[idx].peopleImage = imgUrl
        peopleInfoList[idx].addFlag = true
        that.setData({peopleInfoList: peopleInfoList})
      },
      fail(res) {
        return
      }
    })
  },

  async deletePersonImg(e) {
    var idx = e.currentTarget.dataset.idx
    if (this.data.peopleInfoList[idx].addFlag === false && this.data.peopleInfoList[idx].peopleImage.length <= 0) {
      return
    }

    var flag = false
    await wx.showModal({
      title: '提示',
      content: '确认要删除照片吗'
    }).then(res => {
      if (res.cancel) {
        flag = true
      }
    })

    if (flag) {
      return
    }

    var peopleInfoList = this.data.peopleInfoList
    peopleInfoList[idx].addFlag = false
    peopleInfoList[idx].peopleImage = ''
    this.setData({peopleInfoList: peopleInfoList})
  },

  modifyPeopleName(e) {
    var v = e.detail.value
    var idx = e.currentTarget.dataset.idx
    var peopleInfoList = this.data.peopleInfoList
    peopleInfoList[idx].peopleName = v
    this.setData({peopleInfoList: peopleInfoList})
  },

  modifyPeopleRole(e) {
    var v = e.detail.value
    var idx = e.currentTarget.dataset.idx
    var peopleInfoList = this.data.peopleInfoList
    peopleInfoList[idx].peopleRole = v
    this.setData({peopleInfoList: peopleInfoList})
  },

  async selectImg(e) {
    var idx = e.currentTarget.dataset.index
    var that = this
    if (idx !== this.data.imgList.length - 1) {
      var urls = []
      urls.push(that.data.imgList[idx])
      that.setData({previewFlag: true})
      await wx.previewImage({
        current: urls[0],
        urls: urls
      })
      
      return
    }

    var cnt = 2 - this.data.imgList.length
    that.setData({
      chooseFlag: true,
      uploadFlag: true
    })
    await wx.chooseImage({
      count: cnt,
      sourceType:['album', 'camera'],
      success(res) {
        var imgList = that.data.imgList
        var imgUrl = res.tempFilePaths[0]
        imgList.splice(imgList.length - 1, 0, imgUrl)
        that.setData({imgList: imgList})
      },
      fail(res) {
        return
      }
    })
  },

  async deleteImg(e) {
    var idx = e.currentTarget.dataset.index
    if (this.data.imgList.length < 6 && idx === this.data.imgList.length - 1) {
      return
    }

    var flag = false
    await wx.showModal({
      title: '提示',
      content: '确认要删除照片吗'
    }).then(res => {
      if (res.cancel) {
        flag = true
      }
    })

    if (flag) {
      return
    }

    var imgList = this.data.imgList
    imgList.splice(idx, 1)
    this.setData({ imgList: imgList })
  },

  formatBofang(bofang) {
    var str = bofang.trim()
    // 全是空白字符
    if (str.length === 0) {
      return str
    }


    // 分割，如果没有顿号则返回包含字符串本身的数组
    return str.split('、')
  },

  async onSubmit(e) {
    var that = this
    var name = e.detail.value.name
    var engName = e.detail.value.engName
    var bofang = e.detail.value.bofang
    var duration = parseInt(e.detail.value.duration)
    var gaishu = e.detail.value.gaishu
    var jianjie = e.detail.value.jianjie
    var time = this.data.time
    var language = e.detail.value.language
    var type = e.detail.value.type
    var peopleInfoList = this.data.peopleInfoList
    peopleInfoList[0].peopleName = e.detail.value.peopleName1
    peopleInfoList[1].peopleName = e.detail.value.peopleName2
    peopleInfoList[2].peopleName = e.detail.value.peopleName3
    peopleInfoList[0].peopleRole = e.detail.value.peopleRole1
    peopleInfoList[1].peopleRole = e.detail.value.peopleRole2
    peopleInfoList[2].peopleRole = e.detail.value.peopleRole3 

    if (name.length === 0 || engName.length === 0 || gaishu.length === 0 || jianjie.length === 0 
      ||  e.detail.value.duration === 0 || time.length === 0) {
      wx.showToast({
        title: '请填写内容',
        icon: 'error',
        duration: 1000
      })

      return
    }

    if (duration <= 0) {
      wx.showToast({
        title: '请输入正确的放映时长!',
        icon: 'none',
        duration: 1000
      })

      return
    }

    if (this.data.imgList.length === 1) {
      wx.showToast({
        title: '请选择影片照!',
        icon: 'none',
        duration: 1000
      })

      return
    } else if (this.data.imgList.length > 1 && this.data.uploadFlag) {
      await wx.cloud.uploadFile({
        cloudPath: 'userPhoto/' + Date.now() + '.jpg', // 上传至云端的路径
        filePath: that.data.imgList[0], // 小程序临时文件路径
      }).then(res => {
        var imgList = that.data.imgList
        imgList[0] = res.fileID
        that.setData({imgList: imgList})
      }) 
    }

    var people = []
    var peopleimage = []
    var peoplestatus = []

    for (let i = 0; i < 3; ++i) {
      people.push(peopleInfoList[i].peopleName)
      if (peopleInfoList[i].addFlag) {
        await wx.cloud.uploadFile({
          cloudPath: 'userPhoto/' + Date.now() + '.jpg', // 上传至云端的路径
          filePath: peopleInfoList[i].peopleImage, // 小程序临时文件路径
        }).then(res => {
          peopleInfoList[i].peopleImage = res.fileID
        })
      }
      peopleimage.push(peopleInfoList[i].peopleImage)
      peoplestatus.push(peopleInfoList[i].peopleRole)
    }

    if (this.data.editFlag) {
      await db.collection('movies').doc(that.data.id).update({
        data:{
            title: name,
            poster: that.data.imgList[0],
            bofang: that.formatBofang(bofang),
            duration: duration,
            translation: engName,
            gaishu: gaishu,
            jianjie: jianjie,
            language: language,
            type: type,
            people: people,
            peopleimage: peopleimage,
            peoplestatus: peoplestatus,
            time: time
        }
      }).then(res => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
      })

      return
    }
    await db.collection('movies').add({
      data: {
        title: name,
        poster: that.data.imgList[0],
        bofang: that.formatBofang(bofang),
        duration: duration,
        translation: engName,
        gaishu: gaishu,
        jianjie: jianjie,
        language: language,
        type: type,
        people: people,
        peopleimage: peopleimage,
        peoplestatus: peoplestatus,
        time: time
      }
    }).then(res => {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1000
      })
    })
  }
})